﻿using System;
using System.Data.Entity;
using System.Linq;
using Store.Web.Models;

namespace Store.Web.Services
{
    public class CustomerService
    {
        private readonly string _connectionString;
        public CustomerService(string connectionString)
        {
            _connectionString = connectionString;
        }

        public Customer GetCustomer(int customerId)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                return storeDbContext.Customers
                    .Include(c => c.Addresses)
                    .FirstOrDefault(c => c.Id == customerId);
            }
        }

        /// <summary>
        /// Authenticates a customer
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Customer Authenticate(string email, string password)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                return storeDbContext.Customers
                    .Include(c => c.Addresses)
                    .FirstOrDefault(c => string.Equals(c.Email, email, StringComparison.InvariantCultureIgnoreCase) && string.Equals(c.Password, password, StringComparison.InvariantCultureIgnoreCase));
            }
        }


        public void UpdateProduct(Product product)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                storeDbContext.Entry<Product>(product).State = System.Data.EntityState.Modified;
                storeDbContext.SaveChanges();
            }
        }

        public void AddAddress(int customerId, Address address)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                var customer = storeDbContext.Customers.Include("Addresses").Single(c => c.Id == customerId);
                customer.Addresses.Add(address);
                storeDbContext.SaveChanges();
            }
        }
    }
}